package me.tuyou.classloader;

import java.io.*;

/**
 * @author tuyou_cd
 * @date 2021/4/14 11:19
 */
public class BreakDelegateClassLoader extends ClassLoader {

    private String classPath;

    public BreakDelegateClassLoader(String classPath){
        this.classPath = classPath;
    }

    @Override
    public Class<?> findClass(String arg0) throws ClassNotFoundException {
        byte[] data = getData(arg0);
        if(data == null){
            throw new ClassNotFoundException();
        }
        return defineClass(arg0, data, 0, data.length);
    }

    private byte[] getData(String className){
        String path = classPath + File.separatorChar + className.replace('.', File.separatorChar) + ".class";
        try {
            InputStream is = new FileInputStream(path);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int count = 0;
            while((count = is.read(buffer)) != -1){
                out.write(buffer, 0, count);
            }
            return out.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected Class<?> loadClass(String name, boolean resolve) throws ClassNotFoundException {
        synchronized (getClassLoadingLock(name)) {
            Class<?> c = findLoadedClass(name);
            if (c == null) {
                c = findClass(name);
            }
            if (resolve) {
                resolveClass(c);
            }
            return c;
        }
    }
}
